package com.example.apple.printingroommanagementsystem;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;

/**
 * Created by apple on 17/2/25.
 */
public class departmentone extends Fragment {
    Button addDepart,editorDepart,deleteDepart;
    ListView departList;
    ArrayList<MediaItem> mediaItems;
    MyAdapter myAdapter;
    SharedPreferences preferences;
    String token,ip;
    Button departmentOk,departmentNo;
     EditText addDepartEditText;
    ImageView xuanzhuantupian2;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.department_interface_one,container,false);
        departList = (ListView) view.findViewById(R.id.departList);
        xuanzhuantupian2 =(ImageView) view.findViewById(R.id.xuanzhuantupian2);
        departList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.showContextMenu();
            }
        });

        departList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                return false;
            }
        });

        addDepart = (Button)view.findViewById(R.id.tab_btn_add);
        addDepart.setOnClickListener(new addDepartMethods());
     //   editorDepart = (Button)view.findViewById(R.id.editorDepart);
//        editorDepart.setOnClickListener(new editorDepartMethods());
   //     deleteDepart = (Button)view.findViewById(R.id.deleteDepart);
//        deleteDepart.setOnClickListener(new deleteDepartMethods());
        preferences = getActivity().getSharedPreferences("ure", Activity.MODE_PRIVATE);
        ip = "http://a.xl18z.cn/api/users/list";
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //  Log.d("mediaItems-->",mediaItems.get(0).id.toString());
        token = preferences.getString("token","");
        Log.d("--->0",token);
        getDepartmentData();
        this.registerForContextMenu(departList);
        final Handler handler = new Handler();
        //创建一个Runnable
        Runnable task = new Runnable() {

            public void run() {
                handler.postDelayed(this, 120);
                xuanzhuan();
            }
        };
        handler.post(task);//启动定时器

    }
    public void xuanzhuan(){
        ValueAnimator animator = ValueAnimator.ofFloat(xuanzhuantupian2.getRotationY(),xuanzhuantupian2.getRotationY()+35);
        animator.setDuration(120).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float current = (float)animation.getAnimatedValue();
                xuanzhuantupian2.setRotationY(current);
                //imageView.setRotationY(current);
            }
        });
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("请选择操作");
        menu.add(0,1, Menu.NONE,"删除");
        menu.add(0,2, Menu.NONE,"编辑");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case 1:
                deleteDepartMethods(item);
                break;
            case 2:
                 editorDepartMethods(item);
                break;
        }
        return super.onContextItemSelected(item);
    }

    public void editorDepartMethods(MenuItem item){
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        final String id = ((TextView)menuInfo.targetView.findViewById(R.id.item_id)).getText().toString();
        final String name =((TextView)menuInfo.targetView.findViewById(R.id.item_name)).getText().toString();
        final AlertDialog builder = new AlertDialog.Builder(getContext()).create();
        LayoutInflater iInflater = LayoutInflater.from(getContext());
        View v = iInflater.inflate(R.layout.department_addinterface, null);
        builder.setView(v);
        builder.show();
        Window window = builder.getWindow();
        window.setContentView(R.layout.department_addinterface);
        departmentNo =(Button) window.findViewById(R.id.departmentNo);
        departmentOk = (Button)window.findViewById(R.id.departmentOk);
        addDepartEditText = (EditText) window.findViewById(R.id.addDepartEditText);
        addDepartEditText.setHint(name);
        String ip ="http://a.xl18z.cn/api/department/update";
        String s= "?"+"name="+addDepartEditText.getText().toString()+"&id="+id+"&token="+token;
        departmentNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });
        departmentOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ip ="http://a.xl18z.cn/api/department/update";
                String s= "?"+"name="+addDepartEditText.getText().toString()+"&id="+id+"&token="+token;
                GetRequest get = new GetRequest();
                get.doGet(ip,s,new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Log.e("edi-->",msg.obj.toString());
                        getDepartmentData();
                        builder.cancel();
                    }
                });
            }
        });
    }
   public void deleteDepartMethods(MenuItem item){
       AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
       String id = ((TextView)menuInfo.targetView.findViewById(R.id.item_id)).getText().toString();
       String ip ="http://a.xl18z.cn/api/department/del";
     //  Log.e("addIDDepartEditText=",addIDDepartEditText.getText().toString());
       String s = "?id="+id+"&token="+token;
       GetRequest get = new GetRequest();
       get.doGet(ip,s,new Handler(){
           @Override
           public void handleMessage(Message msg) {
               super.handleMessage(msg);
               getDepartmentData();
           }
      });
   }

    private void getDepartmentData() {
        GetRequest get = new GetRequest();
        String s = "?"+"token="+token;
//        final ArrayList<MediaItem> med = new ArrayList<>();
        get.doGet(ip,s,new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                mediaItems = new ArrayList<>();
                JSONObject js =(JSONObject) msg.obj;//拿到返回的js对象
                Log.e("de-->",js.toString());
                try {
                    JSONObject jt =  js.getJSONObject("record");
                    JSONArray arr = jt.getJSONArray("deps");
                    for (int i =0;i<arr.length();i++){
                       JSONObject jso =  arr.getJSONObject(i);
                        MediaItem mediaItem = new MediaItem();
                        mediaItem.id = jso.getString("id");
                        mediaItem.name = jso.getString("name");
                        mediaItem.department = "";
                        //把封装好的mediaItem模型加进mediaItems;
                        mediaItems.add(mediaItem);
                    }
                    myAdapter = new MyAdapter(getContext(),mediaItems);
                    departList.setAdapter(myAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        });
    }

    private class addDepartMethods implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.tab_btn_add:
                    final AlertDialog builder = new AlertDialog.Builder(getContext()).create();
                    LayoutInflater iInflater = LayoutInflater.from(getContext());
                    View v2 = iInflater.inflate(R.layout.department_addinterface, null);
                    builder.setView(v2);
                    builder.show();
                    Window window = builder.getWindow();
                    window.setContentView(R.layout.department_addinterface);
                    departmentNo =(Button) window.findViewById(R.id.departmentNo);
                    departmentOk = (Button)window.findViewById(R.id.departmentOk);
                    addDepartEditText = (EditText) window.findViewById(R.id.addDepartEditText);
                    departmentNo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            builder.cancel();
                        }
                    });
                    departmentOk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String ip = "http://a.xl18z.cn/api/department/insert";
                            String s ="?name="+addDepartEditText.getText()+"&token="+preferences.getString("token","");
                            GetRequest get = new GetRequest();
                            get.doGet(ip,s,new Handler(){
                                @Override
                                public void handleMessage(Message msg) {
                                    super.handleMessage(msg);
                                    JSONObject json =(JSONObject) msg.obj;
                                    String str = new String();
                                    try {
                                        str=json.getString("errmsg");
                                        Log.e("--=",str);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                    if (str.equals("ok!")){
                                        Toast.makeText(getContext(),"添加成功",Toast.LENGTH_SHORT).show();
                                        builder.cancel();
                                        getDepartmentData();
                                    }else {
                                        Toast.makeText(getContext(),"添加失败",Toast.LENGTH_SHORT).show();
                                        builder.cancel();
                                    }
                                }
                            });
                        }
                    });
                    break;
            }
        }
    }

}
